package netbayServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.*;

import util.String.StringUtil;
import util.jQgrid.JQGridContainer;
import util.jQgrid.JQGridFormatterUtil;
import util.jQgrid.JQGridRow;
import util.jQgrid.JSONUtil;

import netbay.NetbayUtility;
import netbay.TransactionManager;
import netbay.UserManager;

/**
 * Servlet implementation class ManageGroupServlet
 */
public class ManageGroupServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ManageGroupServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init() {
    	
		String configPath = getServletContext().getRealPath(
				"/WEB-INF/config.properties");
		NetbayUtility.init(configPath);
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as // 8-bit Unicode (e.g., for Czech characters)
        response.setContentType("text/json;charset=utf-8");
        HttpSession session = request.getSession();
        String url = "";
        String userId = ((!StringUtil.isNullOrEmpty((String)(session.getAttribute("userId")))) ? (String)session.getAttribute("userId"): "null");
        if(!(userId.equals("null"))){
        	url = "/ManageGroup.jsp";
        }
        else{
        	url = "/Login.jsp";
        }
        try{
        request.getRequestDispatcher(url).forward(request, response);
			} catch (Exception ex) {
	            ex.printStackTrace();
	        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 request.setCharacterEncoding("UTF-8");
		 response.setContentType("text/json;charset=utf-8");
		 String userPath = request.getServletPath();
		 PrintWriter out = response.getWriter();
	     String strJson = "{}";
	     HttpSession session = request.getSession();
	     if (userPath.equals("/ManageGroupServlet/DisplayPermission")) {
	    	 try {
		    	 String page = request.getParameter("page"); // get the requested page
		         String limit = request.getParameter("rows"); // get how many rows we want to have into the grid
		         String sidx = request.getParameter("sidx"); // get index row - i.e. user click to sort
		         String sord = request.getParameter("sord"); // get the direction
				 UserManager um = new UserManager();
				 List result = null;
				 List all = null;
				 Integer count = 0;
				 result = um.getDisplayPermission(page, limit, sidx, sord);
				 all = um.getDisplayPermission();
				 count = all.size();
			 
				 strJson = JQGridFormatterUtil.getJSON(Integer.parseInt(page), Integer.parseInt(limit), count, result);
				 //out.println(strJson);
	         } catch (Exception ex) {
	        	 strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ;
	         }
	         out.println(strJson);
	     }else  if (userPath.equals("/ManageGroupServlet/SavePermission")) {
	    	 try {
		    	 UserManager um = new UserManager();
		    	 Gson gson = new Gson();
		    	 JsonObject obj = new JsonObject() ;
		    	 Integer id ;
	    		 Integer tcdTracking;
	    		 Integer rdTracking ;
	    		 Integer tcdBilling ;
	    		 Integer rdBilling ;
	    		 Integer manageUsers;
	    		 Integer manageGroups;
	    		 Integer userLog ;
	    		 Integer reTCDTCD ;
	    		 Integer reJPMCTCD ;
	    		 Integer reRDRD ;
	    		 Integer reJPMCRD ;
		    	 JsonArray trade = null;
		    	 
		    	 trade = JSONUtil.convertStringJsonToJSONArray(request.getParameter("data"));
			
		    	 Boolean result = true;
		    	 Boolean end = false;
		    	 while(!end){
			    	 for(int i = 0;i<trade.size();i++){
			    		 obj = trade.get(i).getAsJsonObject();
			    		 id  = gson.fromJson( obj.get("id"), Integer.class);
			    		 tcdTracking = gson.fromJson(obj.get("tcdTracking"), Integer.class);
			    		 rdTracking = gson.fromJson(obj.get("rdTracking"), Integer.class);
			    		 tcdBilling = gson.fromJson(obj.get("tcdBilling"), Integer.class);
			    		 rdBilling = gson.fromJson(obj.get("rdBilling"), Integer.class);
			    		 manageUsers = gson.fromJson(obj.get("manageUsers"), Integer.class);
			    		 manageGroups = gson.fromJson(obj.get("manageGroups"), Integer.class);
			    		 userLog = gson.fromJson(obj.get("userLog"), Integer.class);
			    		 reTCDTCD = gson.fromJson(obj.get("reTCDTCD"), Integer.class);
			    		 reJPMCTCD = gson.fromJson(obj.get("reJPMCTCD"), Integer.class);
			    		 reRDRD = gson.fromJson(obj.get("reRDRD"), Integer.class);
			    		 reJPMCRD = gson.fromJson(obj.get("reJPMCRD"), Integer.class);
			    		 result = um.savePermission(id,tcdTracking,rdTracking,tcdBilling,rdBilling,manageUsers,manageGroups,userLog,reTCDTCD,reJPMCTCD,reRDRD,reJPMCRD);
			    	 }
			    	 end = true;
		    	 }
		    	
		    	 if(end&result){
		    		 
						um.saveLog((String)session.getAttribute("userId"),UserManager.actionEditGroup,"");
					
		    		 strJson = "{\"success\" : \"\"}";
		    	 }else{
		    		 strJson = "{\"error\" : \"Cannot save group.\"}";
		    	 }
	    	 } catch (Exception ex) {
	    		 strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ;
			}
	    	 out.println(strJson);
	     }else if (userPath.equals("/ManageGroupServlet/DeleteGroup")) {
	    	 try {
		    	 Integer id = Integer.parseInt(request.getParameter("id"));
				 UserManager um = new UserManager();
				 boolean resultGroup = false;
				 boolean resultUser = false;
				 String group = um.getGroupById(id);
				 resultGroup = um.deleteGroup(id);
				 resultUser = um.deleteUserByGroup(id);
				 
				 if(resultUser&&resultGroup){
					 um.saveLog((String)session.getAttribute("userId"),UserManager.actionDeleteGroup,group);
					 strJson = "{\"success\": \"\"}";
				 }
	         } catch (Exception ex) {
	        	 strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ;
	         }
	         out.println(strJson);
	     }
	}

}
